package com.admin.scroller.photoorvideo;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.admin.scroller.photoorvideo.fragment.PhotoGrildFragment;
import com.admin.scroller.photoorvideo.fragment.PhotosFragment;
import com.admin.scroller.photoorvideo.utils.PermissionUtil;
import com.admin.scroller.photoorvideo.utils.Res;
import com.admin.scroller.photoorvideo.viewModel.PhotoViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * 图片选择 主 activity
 */
public class PhotoChoseActivity extends AppCompatActivity {

    public static String RESULT_IMAGES="result_image_video";//图片选择返回的key
    public static String IMAGE_SIZE="image_size";//图片选择张数限制的

    public static int ALLOW_SELECTED_SIZE=9;//最高图片选择数量
    //SD卡权限
    private String[] permiss=new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //拍照、视屏录取权限
    private String[] permiss_camera=new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WAKE_LOCK,Manifest.permission.RECORD_AUDIO};
    public static PhotoChoseActivity activity;
    //图片展示类型  0 列表展示 1 grid展示
    public static int TYPE_LIST=0;
    public static int TYPE_GRILD=1;

    public static String BODY_TYPE="body_type";
    //统一数据获取模型
    public static  PhotoViewModel viewModel;

    //actionbar
    private LinearLayout linearBack;
    private LinearLayout linearInfo;
    private TextView textIndex;
    private TextView textAll;
    private TextView textTitle;

    //
    private ArrayList<String> photos=new ArrayList<>();
    private Button btnEnsure;

    private Handler handler=new Handler();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_photo);
        btnEnsure=findViewById(R.id.btn_ensure);
        initActionBar();
        activity=this;
        viewModel=ViewModelProviders.of(this).get(PhotoViewModel.class);
        //申请sd卡读写权限
        boolean p=PermissionUtil.getPermission(permiss,this,PermissionUtil.GET_PERMISSION_STORAGE);
        if(!p){
            getPhotos();
        }
        //加载类型
        int type=getIntent().hasExtra(BODY_TYPE)? getIntent().getIntExtra(BODY_TYPE,TYPE_LIST):TYPE_LIST;
        //最大选择张数
        ALLOW_SELECTED_SIZE=getIntent().hasExtra(IMAGE_SIZE)?getIntent().getIntExtra(IMAGE_SIZE,ALLOW_SELECTED_SIZE):ALLOW_SELECTED_SIZE;
        if(ALLOW_SELECTED_SIZE>1){
            linearInfo.setVisibility(View.VISIBLE);
            textAll.setText(String.valueOf(ALLOW_SELECTED_SIZE));
            textIndex.setText("0");
        }else {
            linearInfo.setVisibility(View.GONE);
        }

        //加载fragment
        if(type==TYPE_LIST) {
            //列表加载
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_body, new PhotosFragment()).commit();
        }else {
            //grid加载
            getSupportFragmentManager().beginTransaction().replace(R.id.fl_body, new PhotoGrildFragment()).commit();
        }

        //返回标记是 1 时表示调用拍照
        viewModel.checkIsTakenPhoto().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer index) {
                if(index==1){
                    takePhoto();
                }
            }
        });

        viewModel.getChosedPhoto().observe(this, new Observer<List<String>>() {
            @Override
            public void onChanged(@Nullable List<String> strings) {
                photos.clear();
                if(strings!=null) {
                    photos.addAll(strings);
                    textIndex.setText(String.valueOf(strings.size()));
                }
            }
        });

        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(photos.size()>0){
                    sendResult(photos);
                }else {
                    finish();
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==PermissionUtil.GET_PERMISSION_STORAGE){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
                //获取到权限
                getPhotos();
            }else {
                //sd卡读取权限获取失败
                Toast.makeText(this,"无SD卡读写权限!",Toast.LENGTH_SHORT).show();
                finish();
            }
        }else if(requestCode==PermissionUtil.GET_PERMISSION_CAMERA){
            boolean allPermission=true;
            for(int t:grantResults){
                if(t!=PackageManager.PERMISSION_GRANTED){
                    allPermission=false;
                }
            }
            if(allPermission){
                takePhoto();
            }else {
                //相机权限获取失败
                Toast.makeText(this,"无相机使用权限!",Toast.LENGTH_SHORT).show();
            }
        }
    }

    //读取照片
    private void getPhotos(){
        viewModel.findFromSdK(this);
    }

    //拍照或者录像
    private void takePhoto(){
        boolean f=PermissionUtil.getPermission(permiss_camera,this,PermissionUtil.GET_PERMISSION_CAMERA);
        if(!f){
            CameraActivity.lanuchForPhoto(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==1002){
                //返回剪切后的视频文件地址
                formatResult(data.getStringExtra("result"));
            }else if(requestCode==CameraActivity.REQUEST_PHOTO){
                if(data.hasExtra("picture")){
                    String photo=data.getStringExtra("picture");
                    //前往照片剪辑页面？？？
                    //返回的拍照地址
                    formatResult(photo);
                }else if(data.hasExtra("video")){
                    //返回的视频进入编辑界面
                    final String video=data.getStringExtra("video");
                    formatResult(video);
//                    handler.postDelayed(new Runnable() {
//                        @Override
//                        public void run() {
//                            Intent intent=new Intent(PhotoChoseActivity.this,VideoCopActivity.class);
//                            intent.putExtra("url",video);
//                            startActivityForResult(intent,1002);
//                        }
//                    },50);
                }
            }
        }
    }


    private void initActionBar(){
        linearBack=findViewById(R.id.linear_back);
        linearInfo=findViewById(R.id.linear_selected_info);
        textIndex=findViewById(R.id.tv_selected);
        textAll=findViewById(R.id.tv_all);
        textTitle=findViewById(R.id.tv_title);
        Res.init(this);
        String appName=getResources().getString(Res.getStringID("app_name"));
        textTitle.setText(appName);
        linearBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void sendResult(ArrayList<String> result){
        Intent intent=new Intent();
        intent.putStringArrayListExtra(RESULT_IMAGES,result);
        setResult(RESULT_OK,intent);
        finish();
    }

    private void formatResult(String path) {
        ArrayList<String> result=new ArrayList<>();
        result.add(path);
        sendResult(result);
    }

}
